import logging
import os, pdb, pprint
import time

from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.http import JsonResponse

from conf.sysConfig import config
from software.utils import fileStore
from software.models import Software, SoftwareType, SoftwareVersion, SoftwareData
from storehouse.models import Storehouse
from user import dataCheck as da
from user.dataCheck import DataCheck
from user.models import Company, FileStore
from order.models import SoftwareOrder
from software.views.view_download import download
from software.views.view_software import tolist

datacheck = DataCheck()
tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")


def orderList(request, *args, **kwargs):
    """
        url: '/order/list/',
        method: 'post',
        inputData: {
            page: data.page,
            maxItem: data.maxItem,
            token: data.token,//用户密钥
            softwareGroup: data.softwareGroup,
            //管理人员0:未处理 1：已处理(包括订单准备中，配送中，完成) 2：归档
            //使用人员,0表示已完成，1表示未完成 2 归档
        },
        resData: {
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum': null,//检索到总条数
            'orderlist': [{
                'orderId': null,//订单id
                'orderNumber': null,//订单号
                'softwareName': null,//软件名
                'warZoneName': null,//用户所属仓库名称
                'companyName': null,//用户所属单位名称
                'version': null,//软件版本
                'orderState': null,//0准备中，1:配送中，2：已完成（无则空字符串""）
                'userName': null,//订单创建用户名
                'createTime': null,//创建时间
                'delieverType': null,//配送方式
                'iconUrl': 'todo',
                'isAgree' 1,2
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam["token"])

    # 从数据库获取软件时的filter条件字典
    filterDict = {}

    if user.userType == '1':
        pass
    elif user.userType == '2':
        if requestParam['softwareGroup'] == '0':
            filterDict['isExamine'] = False
            filterDict['orderUpState'] = '0'
        elif requestParam['softwareGroup'] == '1':
            filterDict['isExamine'] = True
            filterDict['orderUpState'] = '0'
        elif requestParam['softwareGroup'] == '2':
            filterDict['orderUpState'] = '1'
        else:
            data = {
                "code": 1,
                "msg": "softwareGroup Error",
                'totalNum': 0,
                'orderlist': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    # 使用人员 0表示已完成，1表示未完成 2 归档
    elif user.userType == '3':
        filterDict['user'] = user
        if requestParam['softwareGroup'] == '0':
            filterDict['orderState'] = '2'
            filterDict['orderUpState'] = '0'
        elif requestParam['softwareGroup'] == '1':
            filterDict['orderState__in'] = ['0', '1']
            filterDict['orderUpState'] = '0'
        elif requestParam['softwareGroup'] == '2':
            filterDict['orderUpState'] = '1'
        else:
            data = {
                "code": 1,
                "msg": "softwareGroup Error",
                'totalNum': 0,
                'orderlist': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    else:
        data = {
            "code": 1,
            "msg": "userType Error",
            'totalNum': 0,
            'orderlist': []
        }
        logger_request.info(data)
        return JsonResponse(data)

    orders = SoftwareOrder.objects.filter(**filterDict).order_by('-createTime')
    orderList = []
    for orderItem in orders:
        item = {
            'orderId': orderItem.id,
            'orderNumber': orderItem.orderNumber,
            'softwareName': orderItem.softwareVersion.softwareName,
            'warZoneName': orderItem.user.warZone.name,
            'companyName': orderItem.user.company.name,
            'version': orderItem.softwareVersion.version,
            'orderState': orderItem.orderState,
            'userName': orderItem.user.name,
            'createTime': orderItem.createTime.strftime('%Y-%m-%d %H:%M:%S'),
            'delieverType': orderItem.delieverType,
            'isAgree': orderItem.examineState,
            'iconUrl': download(orderItem.softwareVersion.logo.fileName, 'logo',
                                orderItem.softwareVersion.logo.filePath)[1],
            # 'userPhone': orderItem.user.phone
            'orderType': orderItem.isDownload
        }
        orderList.append(item)
    totalNum = len(orderList)
    result = orderList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                requestParam[
                                                                                                    'page'] *
                                                                                                requestParam[
                                                                                                    'maxItem'])]
    data = {
        "code": 0,
        "msg": "success",
        'totalNum': totalNum,
        'orderlist': result
    }
    logger_request.info(data)
    return JsonResponse(data)


def orderDetail(request, *args, **kwargs):
    """
        url: '/order/detail/',
        method: 'post',
        inputData: {
            token: data.token, // 用户的秘钥
            // usertype:data.usertype,//用户类型，管理员
            orderId: data.orderid,//订单id

        },
        resData: {
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'orderNumber': null,//订单号
            'softwareName': null,//软件名
            'version': null,//软件版本
            'iconUrl': null,//软件图标
            'softwareDetails': null,//软件详情
            'softwareType': null,//软件类别
            'size': null,//软件大小
            'orderState': null,//物流状态：0准备中，1:配送中，2：完成  (deliveryType=0,此参数为空字符串)
            'createTime': null,//创建时间
            'userName': null,//订单创建用户名
            'warZoneName': null,//软件所属仓库名称
            'companyName': null,//软件所属单位名称
            'delieverType': null,
        }
    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    order = SoftwareOrder.objects.filter(pk=requestParam['orderId'])
    orderItem = order[0]
    if orderItem.delieverType == '0':
        pass
    elif orderItem.delieverType == '1':
        pass
    else:
        pass

    if orderItem.orderState == '0':
        pass
    elif orderItem.orderState == '1':
        pass
    else:
        pass
    data = {
        "code": 0,
        "msg": "success",
        'orderNumber': orderItem.orderNumber,
        'softwareName': orderItem.softwareVersion.softwareName,
        'version': orderItem.softwareVersion.version,
        'iconUrl': download(orderItem.softwareVersion.logo.fileName, 'logo',
                            orderItem.softwareVersion.logo.filePath)[1],
        'softwareDetails': orderItem.softwareVersion.updateDetails,
        'currentVersionDesc': orderItem.softwareVersion.currentVersionDesc,
        'softwareType': orderItem.softwareVersion.softwareType.softwareType,
        'orderState': orderItem.orderState,
        'createTime': orderItem.createTime.strftime('%Y-%m-%d %H:%M:%S'),
        'userName': orderItem.user.name,
        'warZoneName': orderItem.user.warZone.name,
        'companyName': orderItem.user.company.name,
        'delieverType': orderItem.delieverType,
        'orderType': orderItem.isDownload,
        'downloadurl': download(orderItem.softFile.fileName, 'file', orderItem.softFile.filePath)[1],
        'size': orderItem.softFile.size,
        # 'softList': tolist(orderItem.softwareVersion.file.all(), True),
        'isAgree': orderItem.examineState,
        'userPhone': orderItem.user.phone,
    }
    logger_request.info(data)
    return JsonResponse(data)


def orderDeal(request, *args, **kwargs):
    """
        url: '/order/deal/',
        method: 'post',
        inputData: {
            token: data.token, // 用户的秘钥
            orderId: data.orderId,//订单id
            option: data.option,
            //0:处理、1：状态更改、2：归档、3：恢复
            //1订单状态更改
            status: data.status,//0：准备，1：配送中，2：完成，
            //0订单处理
            result: data.result, //处理结果,0:允许，1：不允许
        },
        resData: {
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    order = SoftwareOrder.objects.filter(pk=requestParam['orderId'])
    orderItem = order[0]
    # 0:处理、1：状态更改、2：归档、3：恢复
    if requestParam['option'] == '0':
        orderItem.isExamine = True
        # 处理结果,0:允许，1：不允许
        if requestParam['result'] == '0':
            orderItem.examineState = '1'
            orderItem.isDownload = True
            if orderItem.delieverType == '0':
                orderItem.orderState = '2'
        elif requestParam['result'] == '1':
            orderItem.examineState = '2'
            orderItem.isDownload = False
            orderItem.orderState = '2'
        else:
            data = {
                "code": 1,
                "msg": "result error",
            }
            logger_request.info(data)
            return JsonResponse(data)
        orderItem.save()
    elif requestParam['option'] == '1':
        # 0：准备，1：配送中，2：完成，
        if requestParam['status'] == '0':
            orderItem.orderState = '0'
        elif requestParam['status'] == '1':
            orderItem.orderState = '1'
        elif requestParam['status'] == '2':
            orderItem.orderState = '2'
        else:
            data = {
                "code": 1,
                "msg": "status error",
            }
            logger_request.info(data)
            return JsonResponse(data)
        orderItem.save()
    elif requestParam['option'] == '2':
        orderItem.orderUpState = '1'
        orderItem.save()
    elif requestParam['option'] == '3':
        orderItem.orderUpState = '0'
        orderItem.save()
    else:
        data = {
            "code": 1,
            "msg": "option error",
        }
        logger_request.info(data)
        return JsonResponse(data)
    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def groupOrderList(request, *args, **kwargs):
    """
            url:'/order/groupList/',
        method:'post',
        inputData:{
            page:data.page,
            maxItem:data.maxItem,
            token:data.token,//用户密钥
            softwareGroup:data.softwareGroup,//管理人员0:未处理 1：已处理(包括订单准备中，配送中，完成) 2：归档
                                             //使用人员,0表示已完成，1表示未完成
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'orderlist':[{
                'orderId':null,//订单id
                'isAgree':null,//0:未处理；1审核通过；2,未通过//
                'orderNumber':null,//订单号
                'userName':null,//订单创建用户名
                'createTime':null,//创建时间
                'softwareList':[{
                    'softwareName':null,//软件名
                    'iconUrl':null,
                    'warZoneName':null,//软件所属仓库名称
                    'companyName':null,//软件所属单位名称
                    'version':null,//软件版本
                    'orderState':null,//0准备中，1:配送中，2：已完成（无则空字符串""）
                    'delieverType':null,///配送方式:0:授权下载；1：光盘, 2:硬盘,3:自由下载
                    'orderType':null,//授权下载：0已授权；1未授权
                }]
            }]
        }
    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = datacheck.getUser(requestParam["token"])
    #  userType
    # userType = user.userType
    filterDict = {}
    if requestParam['softwareGroup'] == '0':
        filterDict['orderState'] = '2'
        filterDict['orderUpState'] = '0'
    elif requestParam['softwareGroup'] == '1':
        filterDict['orderState__in'] = ['0', '1']
        filterDict['orderUpState'] = '0'
    elif requestParam['softwareGroup'] == '2':
        filterDict['orderUpState'] = '1'
    
    filterDict['user'] = user    
    filterDict['orderType'] = '1'    
    # filterDict = {
    #     'user': user,
    #     'orderType': '1',
    # }
    # todo 已删除和未删除
    groupOrderList = SoftwareOrder.objects.filter(**filterDict)
    orderDict = {}
    for groupOrderItem in groupOrderList:
        if groupOrderItem.group_id in orderDict:
            softwareItem = {
                'softwareName': groupOrderItem.softwareVersion.softwareName,
                'iconUrl': download(groupOrderItem.softwareVersion.logo.fileName, 'logo',
                                    groupOrderItem.softwareVersion.logo.filePath)[1],
                'softList': tolist(groupOrderItem.softwareVersion.file.all(), False),
                # 'downloadurl': download(groupOrderItem.softwareVersion.file.fileName, 'file', groupOrderItem.softwareVersion.file.filePath)[1],
                'warZoneName': groupOrderItem.softwareVersion.designUnit.warZone.name,
                'companyName': groupOrderItem.softwareVersion.designUnit.name,
                'version': groupOrderItem.softwareVersion.version,
                'orderState': groupOrderItem.orderState,
                'delieverType': groupOrderItem.delieverType,
                'orderType': groupOrderItem.isDownload
            }
            orderDict[groupOrderItem.group_id]['softwareList'].append(softwareItem)
        else:
            orderDict[groupOrderItem.group_id] = {
                'orderId': groupOrderItem.id,
                'groupId': groupOrderItem.group.id,
                'orderNumber': groupOrderItem.orderNumber,
                'isAgree': groupOrderItem.examineState,
                'groupName': groupOrderItem.group.groupName,
                'userName': groupOrderItem.user.name,
                'createTime': groupOrderItem.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                'softwareList': []
            }
            softwareItem = {
                'softwareName': groupOrderItem.softwareVersion.softwareName,
                'iconUrl': download(groupOrderItem.softwareVersion.logo.fileName, 'logo',
                                    groupOrderItem.softwareVersion.logo.filePath)[1],
                'warZoneName': groupOrderItem.softwareVersion.designUnit.warZone.name,
                'softList': tolist(groupOrderItem.softwareVersion.file.all(), False),
                # 'downloadurl': download(groupOrderItem.softwareVersion.file.fileName, 'file', groupOrderItem.softwareVersion.file.filePath)[1],
                'companyName': groupOrderItem.softwareVersion.designUnit.name,
                'version': groupOrderItem.softwareVersion.version,
                'orderState': groupOrderItem.orderState,
                'delieverType': groupOrderItem.delieverType,
                'orderType': groupOrderItem.isDownload
            }
            orderDict[groupOrderItem.group_id]['softwareList'].append(softwareItem)
    orderList = []
    for item in orderDict.values():
        orderList.append(item)
    totalNum = len(orderList)
    result = orderList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                requestParam[
                                                                                                    'page'] *
                                                                                                requestParam[
                                                                                                    'maxItem'])]
    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "orderList": result
    }
    # pprint.pprint(orderDict)
    logger_request.info(data)
    return JsonResponse(data)
